import React, { Suspense } from 'react'
import { BrowserRouter, Route, Routes, Navigate, useLocation } from "react-router-dom"

import page from "./pages"

import { routerItem } from "../interface"

export default function index() {
    const BeforeEach = ({ children }: { children: JSX.Element | any }) => {
        const location = useLocation()
        const token = localStorage.getItem('token')
        if (!token && location.pathname !== '/login') {
            return <Navigate to={'/login'} />
        }
        return children
    }

    const mapRouter = (routes: routerItem[]) => {
        const newRouter = routes.map((v: routerItem, i) => {
            return v.path ? <Route key={i} path={v.path} element={<BeforeEach> {v.element} </BeforeEach>}>
                {
                    v.children && mapRouter(v.children)
                }
            </Route>:<Route key={i} path={v.from} element={<Navigate to={v.to} />}></Route>
        })
        return newRouter
    }

    return (
        <Suspense fallback={<h1>loading！！！！</h1>}>
            <BrowserRouter>
                <Routes>
                    {
                        mapRouter(page)
                    }
                </Routes>
            </BrowserRouter>
        </Suspense>
    )
}
